import React, { useState, useEffect } from 'react';
import { Bell, BellOff, Clock, Volume2, VolumeX, Smartphone, Settings } from 'lucide-react';
import NotificationService, { NotificationSettings as NotificationSettingsType } from '../services/notificationService';

interface NotificationSettingsProps {
  onClose?: () => void;
}

const NotificationSettings: React.FC<NotificationSettingsProps> = ({ onClose }) => {
  const [settings, setSettings] = useState<NotificationSettingsType>({
    enabled: true,
    taskReminders: true,
    dailySummary: true,
    weeklyReview: true,
    overdueAlerts: true,
    reminderTime: '09:00',
    soundEnabled: true,
    vibrationEnabled: true
  });
  
  const [permission, setPermission] = useState<NotificationPermission>('default');
  const [isLoading, setIsLoading] = useState(false);
  const [showTestResult, setShowTestResult] = useState<string | null>(null);

  const notificationService = NotificationService.getInstance();

  useEffect(() => {
    // 加载当前设置
    const currentSettings = notificationService.getSettings();
    setSettings(currentSettings);
    
    // 检查权限状态
    const currentPermission = notificationService.getPermissionStatus();
    setPermission(currentPermission);
  }, []);

  const handleSettingChange = (key: keyof NotificationSettingsType, value: any) => {
    const newSettings = { ...settings, [key]: value };
    setSettings(newSettings);
    notificationService.saveSettings({ [key]: value });
  };

  const handleRequestPermission = async () => {
    setIsLoading(true);
    try {
      const newPermission = await notificationService.requestPermission();
      setPermission(newPermission);
      
      if (newPermission === 'granted') {
        setShowTestResult('通知权限已授予！');
      } else {
        setShowTestResult('通知权限被拒绝，请在浏览器设置中手动开启');
      }
    } catch (error) {
      console.error('请求通知权限失败:', error);
      setShowTestResult('请求权限时发生错误');
    } finally {
      setIsLoading(false);
      setTimeout(() => setShowTestResult(null), 3000);
    }
  };

  const handleTestNotification = async () => {
    setIsLoading(true);
    try {
      await notificationService.testNotification();
      setShowTestResult('测试通知已发送！');
    } catch (error) {
      console.error('发送测试通知失败:', error);
      setShowTestResult('发送测试通知失败，请检查权限设置');
    } finally {
      setIsLoading(false);
      setTimeout(() => setShowTestResult(null), 3000);
    }
  };

  const getPermissionStatusText = () => {
    switch (permission) {
      case 'granted':
        return { text: '已授权', color: 'text-green-600', icon: Bell };
      case 'denied':
        return { text: '已拒绝', color: 'text-red-600', icon: BellOff };
      default:
        return { text: '未设置', color: 'text-yellow-600', icon: Bell };
    }
  };

  const permissionStatus = getPermissionStatusText();
  const PermissionIcon = permissionStatus.icon;

  return (
    <div className="bg-theme-bg rounded-xl shadow-lg p-6 max-w-2xl mx-auto">
      {/* 标题 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Settings className="w-6 h-6 text-blue-600" />
          <h2 className="text-xl font-semibold text-theme-text">通知设置</h2>
        </div>
        {onClose && (
          <button
            onClick={onClose}
            className="text-theme-text-muted hover:text-theme-text-secondary transition-colors"
          >
            ✕
          </button>
        )}
      </div>

      {/* 权限状态 */}
      <div className="bg-theme-bg-secondary rounded-lg p-4 mb-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <PermissionIcon className={`w-5 h-5 ${permissionStatus.color}`} />
            <div>
              <h3 className="font-medium text-theme-text">通知权限</h3>
              <p className={`text-sm ${permissionStatus.color}`}>
                状态: {permissionStatus.text}
              </p>
            </div>
          </div>
          
          <div className="flex gap-2">
            {permission !== 'granted' && (
              <button
                onClick={handleRequestPermission}
                disabled={isLoading}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 
                         disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isLoading ? '请求中...' : '授权通知'}
              </button>
            )}
            
            {permission === 'granted' && (
              <button
                onClick={handleTestNotification}
                disabled={isLoading}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 
                         disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isLoading ? '发送中...' : '测试通知'}
              </button>
            )}
          </div>
        </div>

        {showTestResult && (
          <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
            <p className="text-sm text-blue-700">{showTestResult}</p>
          </div>
        )}
      </div>

      {/* 通知开关 */}
      <div className="space-y-4">
        <div className="flex items-center justify-between p-4 bg-theme-bg-secondary rounded-lg">
          <div className="flex items-center gap-3">
            <Bell className="w-5 h-5 text-theme-text-secondary" />
            <div>
              <h3 className="font-medium text-theme-text">启用通知</h3>
              <p className="text-sm text-theme-text-secondary">总开关，关闭后将不会收到任何通知</p>
            </div>
          </div>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={settings.enabled}
              onChange={(e) => handleSettingChange('enabled', e.target.checked)}
              className="sr-only peer"
            />
            <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 
                          peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                          peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                          after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                          after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
          </label>
        </div>

        {/* 具体通知类型 */}
        <div className="space-y-3">
          <div className="flex items-center justify-between p-3 border border-theme-border rounded-lg">
            <div className="flex items-center gap-3">
              <Clock className="w-4 h-4 text-theme-text-secondary" />
              <div>
                <span className="font-medium text-theme-text">任务提醒</span>
                <p className="text-sm text-theme-text-secondary">任务即将到期时提醒</p>
              </div>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={settings.taskReminders}
                onChange={(e) => handleSettingChange('taskReminders', e.target.checked)}
                disabled={!settings.enabled}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 
                            peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                            peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                            after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                            after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                            peer-disabled:opacity-50"></div>
            </label>
          </div>

          <div className="flex items-center justify-between p-3 border border-theme-border rounded-lg">
            <div className="flex items-center gap-3">
              <BellOff className="w-4 h-4 text-theme-text-secondary" />
              <div>
                <span className="font-medium text-theme-text">逾期提醒</span>
                <p className="text-sm text-theme-text-secondary">任务逾期时通知</p>
              </div>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={settings.overdueAlerts}
                onChange={(e) => handleSettingChange('overdueAlerts', e.target.checked)}
                disabled={!settings.enabled}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 
                            peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                            peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                            after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                            after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                            peer-disabled:opacity-50"></div>
            </label>
          </div>

          <div className="flex items-center justify-between p-3 border border-theme-border rounded-lg">
            <div className="flex items-center gap-3">
              <Clock className="w-4 h-4 text-theme-text-secondary" />
              <div>
                <span className="font-medium text-theme-text">每日总结</span>
                <p className="text-sm text-theme-text-secondary">每日工作总结通知</p>
              </div>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={settings.dailySummary}
                onChange={(e) => handleSettingChange('dailySummary', e.target.checked)}
                disabled={!settings.enabled}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 
                            peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                            peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                            after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                            after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                            peer-disabled:opacity-50"></div>
            </label>
          </div>
        </div>

        {/* 提醒时间设置 */}
        <div className="p-4 bg-theme-bg-secondary rounded-lg">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Clock className="w-5 h-5 text-theme-text-secondary" />
              <div>
                <h3 className="font-medium text-theme-text">每日总结时间</h3>
                <p className="text-sm text-theme-text-secondary">设置每日总结通知的时间</p>
              </div>
            </div>
            <input
              type="time"
              value={settings.reminderTime}
              onChange={(e) => handleSettingChange('reminderTime', e.target.value)}
              disabled={!settings.enabled || !settings.dailySummary}
              className="px-3 py-2 border border-theme-border rounded-lg focus:outline-none 
                       focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
            />
          </div>
        </div>

        {/* 声音和震动设置 */}
        <div className="grid grid-cols-2 gap-4">
          <div className="flex items-center justify-between p-3 border border-theme-border rounded-lg">
            <div className="flex items-center gap-3">
              {settings.soundEnabled ? (
                <Volume2 className="w-4 h-4 text-theme-text-secondary" />
              ) : (
                <VolumeX className="w-4 h-4 text-theme-text-secondary" />
              )}
              <span className="font-medium text-theme-text">声音</span>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={settings.soundEnabled}
                onChange={(e) => handleSettingChange('soundEnabled', e.target.checked)}
                disabled={!settings.enabled}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 
                            peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                            peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                            after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                            after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                            peer-disabled:opacity-50"></div>
            </label>
          </div>

          <div className="flex items-center justify-between p-3 border border-theme-border rounded-lg">
            <div className="flex items-center gap-3">
              <Smartphone className="w-4 h-4 text-theme-text-secondary" />
              <span className="font-medium text-theme-text">震动</span>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={settings.vibrationEnabled}
                onChange={(e) => handleSettingChange('vibrationEnabled', e.target.checked)}
                disabled={!settings.enabled}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 
                            peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full 
                            peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] 
                            after:left-[2px] after:bg-theme-bg after:border-theme-border after:border after:rounded-full 
                            after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600 
                            peer-disabled:opacity-50"></div>
            </label>
          </div>
        </div>
      </div>

      {/* 说明信息 */}
      <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <h4 className="font-medium text-blue-800 mb-2">使用说明</h4>
        <ul className="text-sm text-blue-700 space-y-1">
          <li>• 任务提醒会在任务到期前30分钟发送</li>
          <li>• 每日总结会在设定时间自动发送</li>
          <li>• 逾期提醒会在任务逾期时立即发送</li>
          <li>• 关闭浏览器后，部分通知可能无法正常发送</li>
        </ul>
      </div>
    </div>
  );
};

export default NotificationSettings;
